import axios from 'axios'

const API_BASE_URL = 'http://localhost:8000/api'

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export const setAuthToken = (token) => {
  if (token) {
    api.defaults.headers.common['Authorization'] = `Bearer ${token}`
  } else {
    delete api.defaults.headers.common['Authorization']
  }
}

// API 方法
export default {
  auth: {
    login: (credentials) => api.post('/auth/login', credentials),
    register: (userData) => api.post('/auth/register', userData),
    logout: () => api.post('/auth/logout'),
    changePassword: (passwordData) => api.post('/auth/change-password', passwordData)
  },
  
  users: {
    getMe: () => api.get('/users/me'),
    updateProfile: (id, userData) => api.put(`/users/${id}`, userData),
    getUser: (id) => api.get(`/users/${id}`)
  },
  
  exams: {
    getExams: (params) => api.get('/exams', { params }),
    getExam: (id) => api.get(`/exams/${id}`),
    getExamDetail: (id) => api.get(`/exams/${id}`),
    getAvailableExams: () => api.get('/exams/available'),
    getExamQuestions: (id) => api.get(`/questions/exam/${id}/student`),
    createExam: (examData) => api.post('/exams', examData),
    updateExam: (id, examData) => api.put(`/exams/${id}`, examData),
    deleteExam: (id) => api.delete(`/exams/${id}`),
    getExamStats: () => api.get('/exams/stats/count')
  },
  
  questions: {
    getQuestions: (params) => api.get('/questions', { params }),
    getQuestion: (id) => api.get(`/questions/${id}`),
    createQuestion: (questionData) => api.post('/questions', questionData),
    updateQuestion: (id, questionData) => api.put(`/questions/${id}`, questionData),
    deleteQuestion: (id) => api.delete(`/questions/${id}`),
    getExamQuestions: (examId) => api.get(`/questions?exam_id=${examId}`),
    getQuestionCount: (examId) => api.get(`/questions/exam/${examId}/count`)
  },
  
  scores: {
    getScores: (params) => api.get('/scores', { params }),
    getScoreDetail: (id) => api.get(`/scores/${id}`),
    submitExam: (examId, answers) => api.post('/scores/submit', { exam_id: examId, answers }),
    getExamRank: (examId) => api.get(`/scores/rank/${examId}`)
  }
}